package com.example.boos.ui.home;

import android.os.Bundle;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.example.boos.HttpUtil.MyPost;
import com.example.boos.MainActivity;
import com.example.boos.R;
import com.example.boos.context.BossInfo;
import com.example.boos.pojo.Food;
import com.example.boos.pojo.FoodType;
import com.example.boos.util.MyThreadPool;
import com.example.boos.util.ShowPopuWIndow;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

import se.emilsjolander.stickylistheaders.StickyListHeadersListView;

public class HomeFragment extends Fragment {

    TextView mSubTitle;

    LinearLayout mLists;
    FrameLayout.LayoutParams mListsParams;

    public static   View popView;


    public static View view ;
    public static List<FoodType> leftData;
    public static List<Food> rightData;
    private static ListView left;
    private static StickyListHeadersListView right;
    public static ImageView bg;
    private static TextView title;
    private static Button addFoodType;
    private static Button addFood;
    private static LeftAdapter leftAdapter;
    private static RightAdapter rightAdapter;
    // 更新店铺图片
    public static void updateStoreImage(String url){
        Glide.with(view).load(url).into(bg);
    }
    // 更新菜品图片
    public static void updateFoodImage(String url){
        rightAdapter.update(url);
    }

    // 通知更新
    public static void updateLeftALL(List<FoodType> data){
        leftAdapter.updateAll(data);
    }
    public static void updateRightAll(List<Food> data){
        rightAdapter.updateAll(data);
    }

    public static void updateLeft(){
        leftAdapter.notifyDataSetChanged();
    }
    public static void updateRight(){
        rightAdapter.notifyDataSetChanged();
    }

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        if(view == null){
            view = inflater.inflate(R.layout.fragment_home, container, false);
            leftData = new ArrayList<>();
            rightData = new ArrayList<>();
            //=====================================
            //HomeFragment 中的组件
            left = view.findViewById(R.id.left_list);
            right = view.findViewById(R.id.right_list);
            bg = view.findViewById(R.id.bg);
            title = view.findViewById(R.id.title);
            addFoodType = view.findViewById(R.id.addFoodType);
            addFood = view.findViewById(R.id.addFood);
            mSubTitle = (TextView) view.findViewById(R.id.subtitle);
            //===========
            mLists = (LinearLayout) view.findViewById(R.id.lists); //主体内容布局
            mListsParams = (FrameLayout.LayoutParams) mLists.getLayoutParams();
            // ================ 两个 ListView 的初始化 =========================
            leftAdapter = new LeftAdapter(MainActivity.getMainActivity(),leftData);
            rightAdapter = new RightAdapter(MainActivity.getMainActivity(),rightData);
            left.setAdapter(leftAdapter);
            right.setAdapter(rightAdapter);
            // 设置监听器
            left.setOnTouchListener(new ListParentOnTouchListener(mDelegate));
            right.setOnTouchListener(new ListParentOnTouchListener(mDelegate));
        }

        if(BossInfo.currentStore != null){
            // 更新一下店铺图片和店铺名
            Glide.with(view).load(BossInfo.currentStore.getStoreImage()).into(bg);
            title.setText(BossInfo.currentStore.getStoreName());
        }




        // 上传店铺图片
        bg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MainActivity.isStoreIamge = true;
                ShowPopuWIndow.showPopueWindow(getActivity(),1);
            }
        });

        right.setOnScrollListener(new AbsListView.OnScrollListener() { // 菜品滚动的事件监听
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem,
                                 int visibleItemCount, int totalItemCount) {
                try {
                    long cId = rightAdapter.getHeaderId(firstVisibleItem);
                    leftAdapter.updateSelected(getLeftPosition(cId));

                } catch (Exception e) {

                }
            }
        });

        left.setOnItemClickListener(new AdapterView.OnItemClickListener() { // 添加菜品类型的事件监听 选中菜品类型项
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                    // 选中菜单项高亮
                    leftAdapter.updateSelected(i);
                    // 找到菜单类型的第一项
                    right.setSelection(getRightPosition(i));

            }
        });
        // 添加菜品类型
        addFoodType.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showAddTypeWind();
            }
        });

        // 添加菜品
        addFood.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showAddFoodWind();
            }
        });

        return view;
    }

    // 根据菜单项获取其第一个菜品的位置
    private int getRightPosition(int leftPosition){
        int position = 0;
        // 获取 菜品类型名称
        Integer typeId = leftData.get(leftPosition).getId();
        // 获取到该菜单类型的第一个菜品
        for(int i=0;i<rightData.size();i++){
            Integer tempTypeId = rightData.get(i).getFoodTypeId();
            if(tempTypeId .equals(typeId)){
                position = i;
                break;
            }
        }
        return position;
    }

    //  根据菜单项Id找到菜单项的索引
    private int getLeftPosition(long cId){
        int position = 0;
        Integer ccid = (int)cId;
        for (int i = 0;i<leftData.size();i++){
            if (rightData.get(i).getId().equals(ccid)) {
                position = i;
                break;
            }
        }
        return position;
    }


    TouchDelegate mDelegate = new TouchDelegate() { //
        @Override
        void onTouchDone(View view,TouchOrientation orientation,float offset) {
            if(isAdded()){
                if (orientation == TouchOrientation.DOWN_2_UP) {//往上

                    int topMargin = Tools.px2dip(getActivity(),mListsParams.topMargin);
                    int configToolBarHeight = Tools.px2dip(getActivity(),getResources().getDimension(R.dimen.toolbar_height));
                    float configToolBarHeightPx = getResources().getDimension(R.dimen.toolbar_height);
                    float configTopMarginPx = getResources().getDimension(R.dimen.top_margin);
                    if (topMargin > configToolBarHeight) {
                        ListParentOnTouchListener.SCROLL_ENABLE = false;
                        float top = (mListsParams.topMargin - offset);
                        if (top < configToolBarHeightPx) top = configToolBarHeightPx;
                        mListsParams.setMargins(mListsParams.leftMargin, (int) top, mListsParams.rightMargin, mListsParams.bottomMargin);
//                    mLists.requestLayout();
                        mLists.setLayoutParams(mListsParams);
                        float scale = top / configTopMarginPx;
                        title.setAlpha(scale);
                        mSubTitle.setAlpha(1-scale);
                    }else{
                        title.setAlpha(0);
                        mSubTitle.setAlpha(1);
                        ListParentOnTouchListener.SCROLL_ENABLE = true;
                    }
                }else if (orientation == TouchOrientation.UP_2_DOWN) {//往下
                    int topMargin = Tools.px2dip(getActivity(),mListsParams.topMargin);
                    int configTopMargin = Tools.px2dip(getActivity(),getResources().getDimension(R.dimen.top_margin));
                    float configTopMarginPx = getResources().getDimension(R.dimen.top_margin);
                    if (topMargin == configTopMargin) {
                        ListParentOnTouchListener.SCROLL_ENABLE = true;
                        title.setAlpha(1);
                        mSubTitle.setAlpha(0);
                    }else{
                        ListParentOnTouchListener.SCROLL_ENABLE = false;
                        float top = (mListsParams.topMargin + offset);
                        if (top > configTopMarginPx) top = configTopMarginPx;
                        mListsParams.setMargins(mListsParams.leftMargin, (int) top, mListsParams.rightMargin, mListsParams.bottomMargin);
//                    mLists.requestLayout();
                        mLists.setLayoutParams(mListsParams);
                        float scale = top / configTopMarginPx;
                        title.setAlpha(scale);
                        mSubTitle.setAlpha(1-scale);
                    }

                }
            }

        }
    };

    // 添加菜品类型的窗口
    private void showAddTypeWind(){
        if(isAdded()){
            popView = View.inflate(getActivity(),R.layout.add_food_type,null);
            Button bt_add = (Button) popView.findViewById(R.id.addFoodType);
            Button bt_cancle = (Button) popView.findViewById(R.id.cancelAddFoodType);
            EditText name = (EditText) popView.findViewById(R.id.AddfoodTypeName);
            //获取屏幕宽高
            int weight = getResources().getDisplayMetrics().widthPixels;
            int height = getResources().getDisplayMetrics().heightPixels*1/3;

            final PopupWindow popupWindow = new PopupWindow(popView,weight,height);
            // popupWindow.setAnimationStyle(R.style.anim_popup_dir);
            popupWindow.setFocusable(true);
            //点击外部popueWindow消失
            popupWindow.setOutsideTouchable(true);

            bt_add.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    // 发送添加请求
                    MyThreadPool.doJob(new Runnable() {
                        @Override
                        public void run() {
                            FoodType foodType = new FoodType();
                            foodType.setFoodTypeName(name.getText().toString());
                            foodType.setStoreId(BossInfo.currentStoreId);
                            foodType = (FoodType)MyPost.doPost("addFoodType",foodType);
                            leftData.add(foodType);
                            // 通知刷新
                            Message msg = new Message();
                            msg.what = 2;
                            MainActivity.handler.sendMessage(msg);
                        }
                    });
                    popupWindow.dismiss();
                }
            });



            bt_cancle.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    popupWindow.dismiss(); // 隐藏popupWindow
                }
            });

            //popupWindow消失屏幕变为不透明
            popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
                    lp.alpha = 1.0f;
                    getActivity().getWindow().setAttributes(lp);
                }
            });
            //popupWindow出现屏幕变为半透明
            WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
            lp.alpha = 0.5f;
            getActivity().getWindow().setAttributes(lp);
            popupWindow.showAtLocation(popView, Gravity.BOTTOM,0,50);
        }

    }

    // 添加菜品的框
    private void showAddFoodWind(){
        if(isAdded()){
            popView = View.inflate(getActivity(),R.layout.add_food,null);
            Button bt_add = (Button) popView.findViewById(R.id.btn_addFood);
            Button bt_cancle = (Button) popView.findViewById(R.id.cancelAddFood);
            EditText foodName = (EditText) popView.findViewById(R.id.addFoodName);
            EditText foodPrice = popView.findViewById(R.id.addFoodPrice);
            EditText foodInfo = popView.findViewById(R.id.addFoodInfo);
            TextView foodImageSrc = popView.findViewById(R.id.foodImageSrc);
            ImageView foodImage = popView.findViewById(R.id.addFoodImage);
            Spinner foodType = popView.findViewById(R.id.addFoodType);

            // 设置数据
            List<String> foodTypeName = new ArrayList<>();
            for(FoodType y : HomeFragment.leftData){
                foodTypeName.add(y.getFoodTypeName());
            }
            // 适配器
            ArrayAdapter<String> adapterType = new ArrayAdapter<>(getActivity(), R.layout.spinner_item,foodTypeName);
            // 设置适配器
            foodType.setAdapter(adapterType);

            //获取屏幕宽高
            int weight = getResources().getDisplayMetrics().widthPixels;
            int height = getResources().getDisplayMetrics().heightPixels;

            final PopupWindow popupWindow = new PopupWindow(popView,weight,height);
            // popupWindow.setAnimationStyle(R.style.anim_popup_dir);
            popupWindow.setFocusable(true);
            //点击外部popueWindow消失
            popupWindow.setOutsideTouchable(true);

            foodImage.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ShowPopuWIndow.showPopueWindow(getActivity(),2);
                }
            });

            bt_add.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Food food = new Food();
                    String s = foodImageSrc.getText().toString();
                    // 获取到其他信息
                    String info = foodName.getText().toString();
                    if("".equals(info)){
                        Toast.makeText(getContext(),"请输入菜品名称！",Toast.LENGTH_SHORT).show();
                        return;
                    }
                    food.setFoodName(info);
                    info = foodPrice.getText().toString();
                    if("".equals(info)){
                        Toast.makeText(getContext(),"请输入菜品金额！",Toast.LENGTH_SHORT).show();
                        return;
                    }
                    food.setFoodPrice(Float.parseFloat(info));
                    info = foodInfo.getText().toString();
                    if("".equals(info)){
                        Toast.makeText(getContext(),"请输入菜品描述！",Toast.LENGTH_SHORT).show();
                        return;
                    }
                    food.setFoodInfo(info);
                    Integer foodTypeId = leftData.get(foodType.getSelectedItemPosition()).getId();
                    food.setFoodTypeId(foodTypeId);
                    food.setFoodTypeName(leftData.get(foodType.getSelectedItemPosition()).getFoodTypeName());
                    food.setFoodStatus(1);
                    food.setFoodStock(1);
                    food.setStoreId(BossInfo.currentStoreId);
                    // 先上传到Oss服务器 返回Url字符串
                    MyThreadPool.doJob(new Runnable() {
                        @Override
                        public void run() {
                           food.setFoodImage((String) MyPost.uploadImage("getImageUrl",s));
                           // 添加到服务器中
                            food.setId((Integer)MyPost.doPost("addFood",food));
                            Boolean isAddFood = false;
                            if(food.getId() != null){
                                isAddFood = true;
                                // 添加成功
                                rightData.add(food);
                                // 排序
                                rightData.sort(new Comparator<Food>() {
                                    @Override
                                    public int compare(Food o1, Food o2) {
                                        return o1.getFoodTypeId()-o2.getFoodTypeId();
                                    }
                                });
                            }
                            Message msg = new Message();
                            msg.what =7;
                            msg.obj = isAddFood;
                            MainActivity.handler.sendMessage(msg);
                        }
                    });
                    popupWindow.dismiss();
                }
            });





            bt_cancle.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    popupWindow.dismiss(); // 隐藏popupWindow
                }
            });

            //popupWindow消失屏幕变为不透明
            popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
                    lp.alpha = 1.0f;
                    getActivity().getWindow().setAttributes(lp);
                }
            });
            //popupWindow出现屏幕变为半透明
            WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
            lp.alpha = 0.5f;
            getActivity().getWindow().setAttributes(lp);
            popupWindow.showAtLocation(popView, Gravity.BOTTOM,0,50);
        }
    }
}